package com.minshenglife.zanzan.web.weixin.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.minshenglife.commons.security.utils.AccessTokenUtils;
import com.minshenglife.commons.security.utils.pp.UserIdentify;
import com.minshenglife.commons.security.utils.pp.UserIdentify.UserType;
import com.minshenglife.zanzan.entity.EMOUserGroup;
import com.minshenglife.zanzan.entity.weixin.ArticleTodb;
import com.minshenglife.zanzan.entity.weixin.AutomaticReply;
import com.minshenglife.zanzan.entity.weixin.Keyword;
import com.minshenglife.zanzan.entity.weixin.Material;
import com.minshenglife.zanzan.pub.message.MessageUtil;
import com.minshenglife.zanzan.pub.message.resp.BaseMessage;
import com.minshenglife.zanzan.pub.message.resp.NewsMessage;
import com.minshenglife.zanzan.pub.message.resp.TextMessage;
import com.minshenglife.zanzan.pub.message.resp.model.Article;
import com.minshenglife.zanzan.pub.utils.WXKeys;
import com.minshenglife.zanzan.service.AccessTokenService;
import com.minshenglife.zanzan.service.ArticleService;
import com.minshenglife.zanzan.service.AutomaticReplyService;
import com.minshenglife.zanzan.service.EMOUserGroupService;
import com.minshenglife.zanzan.service.KeywordService;
import com.minshenglife.zanzan.service.MaterialService;
import com.nationsky.pub.utils.StringUtils;
  
/** 
 * EMO微信核心服务类 
 *  
 * @author jianghaibo 
 * @date 2013-05-20 
 */  
@Component
public class EMOCoreService {  
	Logger log = LoggerFactory.getLogger(EMOCoreService.class);
	@Resource
	WXReviewService wxreviewService;
	@Resource
	EMOWXMenuEventService emowxMenuEventService;
	@Resource
	EMOUserGroupService emoUserGroupService;
	@Resource
	AutomaticReplyService automaticReplyService;
	@Resource
	KeywordService keywordService;
	@Resource
	MaterialService materialService;
	@Resource
	ArticleService articleService;
	@Resource
	AccessTokenService accessTokenService;
	//服务器跟地址
	String server_address = WXKeys.WX_BASEURL;
	//公众号标识
	String appid = WXKeys.WX_EMO_APPID;
    /** 
     * 处理微信发来的请求 
     *  
     * @param request 
     * @return 
     */  
    public  String processRequest(HttpServletRequest request) {  
    	log.debug("start processRequest method ===处理微信发来的请求");
        String respMessage = null;  
        
        try {  
            // 默认返回的文本消息内容  
            String respContent = "";  
  
            // xml请求解析  
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            
            log.debug("get message is "+requestMap.toString());
            // 发送方帐号（open_id）  
            String fromUserName = requestMap.get(WXKeys.WX_FROMUSERNAME);  
            // 公众帐号  
            String toUserName = requestMap.get(WXKeys.WX_TOUSERNAME);  
            // 消息类型  
            String msgType = requestMap.get(WXKeys.WX_MSGTYPE); 
            // 创建基本消息模板
            BaseMessage baseMessage = new NewsMessage();
            baseMessage.setFromUserName(toUserName);
            baseMessage.setToUserName(fromUserName);
            baseMessage.setFuncFlag(0);
            baseMessage.setCreateTime(new Date().getTime());
            // 文本消息  
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {  
            	String reqContent=StringUtils.processStrings(requestMap.get(WXKeys.WX_CONTENT));
            	System.out.println("微信用户发送的消息是 --> '"+reqContent+"'");
            	EMOUserGroup userGroup = emoUserGroupService.getUserByOpenid(fromUserName);
            	if(userGroup != null){
            		List<Keyword> keyWordList = keywordService.findAllByAppid(appid);
                	Keyword keyWord = null;
    				for (Keyword keyWord2 : keyWordList) {
    					String word = keyWord2.getKeyWord();
    					// 匹配类型(匹配类型(1:全匹配,0:未全匹配)
    					if (keyWord2.getMatchType().equals("1")) {
    						// 当前用户发送的 content 与库中关键词对比
    						if (reqContent.equals(word)) {
    							keyWord = keyWord2;
    							break;
    						}
    						// 匹配类型(匹配类型(1:全匹配,0:未全匹配)
    					} else {
    						// 当前用户发送的 content 与库中关键词对比
    						if (reqContent.indexOf(word) != -1) {
    							keyWord = keyWord2;
    							break;
    						}
    					}
    				}
    				// 关键词不为空
    				if (keyWord != null) {
    					AutomaticReply automaticReply = automaticReplyService.get(keyWord.getAutomaticId());
    					log.debug("素材id为  --》》》"+automaticReply.getMaterialId());
    					Material material = materialService.get(automaticReply.getMaterialId());
    					respMessage = getRespMessageByMaterial(material,baseMessage);
    				}
            	}else{
            		String access_token=AccessTokenUtils.newToken(new UserIdentify(UserType.weixin,fromUserName), String.valueOf(new Date().getTime()));
        			accessTokenService.insertAccessTokenOfNotUser(fromUserName,access_token);//插入页面时效
        			List<Article> list = new ArrayList<Article>();
        			list.add(new Article("查看详细信息请绑定员工号","点击该图文消息进入绑定页面",null,WXKeys.WX_BASEURL+"/jsp/weixin/emo/register.jsp?access_token="+access_token));//"/user/gotoRegister.do?access_token="+access_token
        			NewsMessage newsMessage=new NewsMessage(fromUserName,toUserName,new Date().getTime(),MessageUtil.RESP_MESSAGE_TYPE_NEWS,0,0,null); 
        			newsMessage.setArticles(list);
        			newsMessage.setArticleCount(list.size());
        			respMessage = MessageUtil.newsMessageToXml(newsMessage);
            	}
            	
				
//                TextMessage message = new TextMessage(fromUserName,toUserName,new Date().getTime(),
//                		MessageUtil.RESP_MESSAGE_TYPE_TEXT,0,respContent);                  
//                respMessage = MessageUtil.textMessageToXml(message);
            }  
            // 图片消息  
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {  
//                respContent = "您发送的是图片消息！";  
            }  
            // 地理位置消息  
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {  
//                respContent = "您发送的是地理位置消息！";  
            }  
            // 链接消息  
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {  
//                respContent = "您发送的是链接消息！";  
            }  
            // 音频消息  
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {  
//                respContent = "您发送的是音频消息！";  
            }  
            // 事件推送  
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {  
                // 事件类型  
                String eventType = requestMap.get(WXKeys.WX_EVENT);  
                // 订阅（关注）  
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                	String access_token=AccessTokenUtils.newToken(new UserIdentify(UserType.weixin,fromUserName), String.valueOf(new Date().getTime()));
        			accessTokenService.insertAccessTokenOfNotUser(fromUserName,access_token);//插入页面时效
                	String bindUrl = WXKeys.WX_BASEURL+"/jsp/weixin/emo/register.jsp?access_token="+access_token;
                    respContent = "欢迎您来到民生保险CMO ！请点击下面链接  <a href=\""+bindUrl+"\"> 员工绑定  </a> 进行绑定，绑定后方可查看详细信息！";  
                    TextMessage message = new TextMessage(fromUserName,toUserName,new Date().getTime(),
                    		MessageUtil.RESP_MESSAGE_TYPE_TEXT,0,respContent);                  
                    respMessage = MessageUtil.textMessageToXml(message);
                }  
                // 取消订阅 （关注） 
                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {  
                    // TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息  
                	//取消绑定
                	EMOUserGroup userByOpenid = emoUserGroupService.getUserByOpenid(fromUserName);
                	if(userByOpenid != null && userByOpenid.getEmpId() != null && !userByOpenid.getEmpId().equals("")){
                		emoUserGroupService.EmpUnbound(userByOpenid.getEmpId(),fromUserName);
                	}
                }  
                // 自定义菜单点击事件  
                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {  
//                	NewsMessage newsMessage=new NewsMessage(fromUserName,toUserName,new Date().getTime(),
//                    		MessageUtil.RESP_MESSAGE_TYPE_NEWS,0,0,null);
//                	TextMessage textMessage = new TextMessage(fromUserName,toUserName,new Date().getTime(),
//                    		MessageUtil.RESP_MESSAGE_TYPE_TEXT,0,null); 
                	String key=requestMap.get(WXKeys.WX_EVENTKEY);
                	log.debug("=========请求菜单的key值："+key);
//                	log.debug("request.getContextPath()"+request.getContextPath());
//                	log.debug("request.getRequestURL()"+request.getRequestURL());
                	
                	respMessage = emowxMenuEventService.getEventResult(key,fromUserName,toUserName);
                	
                }  
            }else{
            	respContent = "信息发送有误，请确认。";
            	TextMessage message = new TextMessage(fromUserName,toUserName,new Date().getTime(),
                		MessageUtil.RESP_MESSAGE_TYPE_TEXT,0,respContent);                  
                respMessage = MessageUtil.textMessageToXml(message);
            }
            
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        log.debug("end processRequest method");
        System.out.println("要发送的消息xml是--> "+respMessage);
        
        return respMessage;  
    }
	private String getRespMessageByMaterial(Material material,
			BaseMessage baseMessage) {
		String respMessage = null;
		
		if (material.getMaterialType() != null && material.getMaterialType().equals("text")) {
			TextMessage textMessage = new TextMessage(baseMessage.getToUserName(),baseMessage.getFromUserName(),new Date().getTime(),
            		MessageUtil.RESP_MESSAGE_TYPE_TEXT,0,material.getContent());
			textMessage.setContent(material.getContent());
			respMessage = MessageUtil.textMessageToXml(textMessage);
		} else if(material.getMaterialType() != null && material.getMaterialType().equals("news")){
			// 图文列表
			List<ArticleTodb> articleToDBs = articleService.findByMaterialId(material.getId());
			List<Article> articleList = new ArrayList<Article>();
			// 将首图加到list第一个
			for (ArticleTodb articleToDB : articleToDBs) {
				if (articleToDB.getId().equals(material.getFirstArticleId())) {
					Article article = new Article();
					article.setTitle(articleToDB.getTitle());
					article.setPicUrl(server_address + articleToDB.getPicUrl());
					article.setUrl(articleToDB.getUrl());
					article.setDescription(articleToDB.getDescription());
					articleList.add(article);
					break;
				}
			}
			for (ArticleTodb articleToDB : articleToDBs) {
				if (!articleToDB.getId().equals(material.getFirstArticleId())) {
					Article article = new Article();
					article.setTitle(articleToDB.getTitle());
					article.setPicUrl(server_address + articleToDB.getPicUrl());
					article.setUrl(articleToDB.getUrl());
					article.setDescription(articleToDB.getDescription());
					articleList.add(article);
				}
			}
			NewsMessage newsMessage=new NewsMessage(baseMessage.getToUserName(),baseMessage.getFromUserName(),new Date().getTime(),MessageUtil.RESP_MESSAGE_TYPE_NEWS,0,0,null); 
			newsMessage.setArticles(articleList);
			newsMessage.setArticleCount(articleList.size());
			respMessage = MessageUtil.newsMessageToXml(newsMessage);
		}
		
		return respMessage;
	}  
    
}  